package com.pw.study.arithmetic

import scala.io.StdIn

/**
 * @Desc: 数组模拟队列
 * @author: future
 * @since: 2022/5/23-21:04
 */
object QueueArray {
  def main(args: Array[String]): Unit = {
    //初始化队列
    val queue = new ArrayQueueByFuture(10)
    var key = ""
    while (true) {
      println("show: 表示显示队列")
      println("exit: 表示退出程序")
      println("add: 表示添加队列数据")
      println("get: 表示取出队列数据")
      println("head: 查看队列头的数据")
      println("isFull: 是否队列满。。")
      println("isEmpty: 是否队列空。。")
      key = StdIn.readLine("请输入：")
      key match {
        case "show" => {
          println("显示队列。。。。。")
          queue.showQueue()
        }
        case "isEmpty" => {
          println("队列是否是空。。")
          val btn: Boolean = queue.isEmpty()
        }
        case "add" => {
          println("添加数据：请输入一个数据：")
          val value: Int = StdIn.readInt()
          queue.addQueue(value)
        }
        case "isFull" => {
          val btn: Boolean = queue.isFull()
          println("队列是否满了：" + btn)
        }
        case "get" => {
          println("获取元素：")
          val res = queue.getQueue()

          if (res.isInstanceOf[Exception]) {
            println("result: " + res.asInstanceOf[Exception])
          } else {
            println(s"取出数据是：$res")
          }
        }
        case "head" => {
          val result = queue.headQueue()
          if (result.isInstanceOf[Exception]) {
            println("打印异常：" + result.asInstanceOf[Exception].getMessage)
          } else {
            println("队列头元素值为=" + result)
          }
        }
        case "exit" => {
          println("退出.....")
          System.exit(0)
        }
        case _ => {
          println("other.................")
        }
      }
    }
  }
}

class ArrayQueueByFuture(capacity: Int) {


  /**
   * 判断队列是否空
   *
   * @return
   */
  def isEmpty(): Boolean = {
    println("队列为空。。。。。。。。。。。。。。")
    front == rear
  }

  /**
   * 判断队列是否满
   *
   * @return
   */
  def isFull(): Boolean = {
    rear == maxSize - 1
  }

  val maxSize = capacity
  //数组存储数据
  private val arr = new Array[Int](maxSize)
  //队列头部
  private var front: Int = -1
  //队列尾部
  private var rear: Int = -1


  def headQueue(): Any = {
    if (isEmpty()) {
      return new Exception("队列空。。。。")
    }
    arr(front+1)
  }

  def getQueue(): Any = {
    if (isEmpty()) {
      println("队列空了。。。。")
      return new Exception("队列空。。。。")
    }
    front += 1
    arr(front)
  }

  /**
   * 添加队列元素
   *
   * @param value
   */
  def addQueue(value: Int): Unit = {
    if (isFull()) {
      println("队列满了，无法加入")
      return
    }
    rear += 1
    arr(rear) = value
  }


  /**
   * 显示队列
   */
  def showQueue(): Unit = {
    if (isEmpty()) {
      println("队列空的，没有数据。。。")
      return
    }
    print("[")
    for(i<- front+1 to rear){
      print(+arr(i)+",")
    }
    print("]")
    println("显示队列所有数据。。。。")
  }

}
